/* eslint-disable camelcase */

export function bufferColorTable(gl) {
  const vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  const a_Position = gl.getAttribLocation(gl.program, 'a_Colors');
  gl.enableVertexAttribArray(a_Position);
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.5, 0.5, 0.5, 0.5]), gl.STATIC_DRAW);
}

export function drawBuffer(gl, vertices, key) {
  const vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  const a_Position = gl.getAttribLocation(gl.program, key);
  gl.enableVertexAttribArray(a_Position);
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

  gl.clearColor(0.1, 0.1, 0.0, 0.1);
  gl.clear(gl.COLOR_BUFFER_BIT);
  const n = vertices.length / 2;
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
}

export const VSHADER_SOURCE = `
  attribute vec2 a_Position;
  void main() {
    gl_Position = vec4(a_Position, 0.0, 1.0);
  }
  `;

export const FSHADER_SOURCE = `
  precision mediump float;
  uniform float width;
  uniform float height;
  uniform sampler2D u_Palette;
  uniform sampler2D u_Sampler;
  vec2 reslution =vec2(width,height);

  float unpack8BitVec4IntoFloat(vec4 v, float min, float max) {
    float zeroTo32Bit = v.x + v.y * 256.0 + v.z * 256.0 * 256.0 + v.w * 256.0 * 256.0 * 256.0;
    float zeroToOne = zeroTo32Bit / 256.0 / 256.0 / 256.0;
    // return zeroToOne;
    return (zeroToOne - min) / (max - min);
  }
 
  void main(){
      // gl_FragColor=vec4(gl_FragCoord.xyx/reslution.xyx,1.0);

      if(reslution.y-gl_FragCoord.y < 20.0){
        gl_FragColor=texture2D(u_Palette,gl_FragCoord.xy/reslution.xy);
      }
      else{
        vec4 color =texture2D(u_Sampler,gl_FragCoord.xy/reslution.xy);
        float result = unpack8BitVec4IntoFloat(color * 256.0,-20.0,80.0);
        gl_FragColor=texture2D(u_Palette,vec2(result,1.0));
        // if(color.z>=0.627451032){
        //   gl_FragColor=vec4(0,0,color.z,color.w);
        // }
        // else{
        //   gl_FragColor=vec4(0,0,0,1.0);
        // }
      }
    }
  `;
